﻿using log4net;
using Quartz;
using Quartz.Impl;
using Quartz.Impl.Matchers;
using System;
using System.Collections.Specialized;

namespace QuartzTest
{
    public class Schedule
    {
        private static IScheduler scheduler;
        readonly static ILog log = LogManager.GetLogger(typeof(Schedule));
        public static async void StartSchedule()
        {
            try
            {
                // construct a scheduler factory
                NameValueCollection props = new NameValueCollection
                {
                    {"quartz.serializer.type", "binary"},
                    {"quartz.threadPool.maxConcurrency",$"{Environment.ProcessorCount*2}" },//quartz.threadPool.maxConcurrency
                };
                StdSchedulerFactory factory = new StdSchedulerFactory(props);
                // get a scheduler
                scheduler = await factory.GetScheduler();
                //注册任务触发器 ,时间周期从长到短           
                ScheduleAllSecondsJob();
                //scheduler.ListenerManager.AddJobListener(myJobListener, KeyMatcher<JobKey>.KeyEquals(new JobKey("myJobName", "myJobGroup")));
                scheduler.ListenerManager.AddSchedulerListener(new LogSchedulerListener());
                scheduler.ListenerManager.AddJobListener(new LogJobListener(), GroupMatcher<JobKey>.AnyGroup());
                scheduler.ListenerManager.AddTriggerListener(new LogTriggerListener(), GroupMatcher<TriggerKey>.AnyGroup());
                await scheduler.Start();
            }
            catch (Exception ex)
            {
                EE.LogError("start quartz scheduler error:", ex, log);
            }
        }
        public static async void StopSchedule()
        {
            await scheduler.Shutdown();
        }
        private static void ScheduleAllSecondsJob()
        {
            string group = "secondsGroup";
            try
            {                
                ScheduleSecondsJob<RoomCloseJob>("roomCloseJob", group, 58); // 
            }
            catch (Exception ex)
            {
                EE.LogError("ScheduleAllSeconds Fail:", ex, log);
            }
        }
        private static async void ScheduleSecondsJob<T>(string jobName, string group, int interval) where T : IJob
        {
            string triggerName = $"{jobName}Trigger";
            try
            {
                log.Info($"ScheduleSecondsJob  {jobName}，Interval {interval} sec");
                IJobDetail job = JobBuilder.Create<T>()
                      .WithIdentity(jobName, group)
                      .Build();
                ITrigger trigger = TriggerBuilder.Create()
                          .WithIdentity(triggerName, group)
                          .StartNow()
                          .WithSimpleSchedule(x => x
                              .WithIntervalInSeconds(interval) //execute  eVery 2 minute
                              .RepeatForever())
                          .Build();
                await scheduler.ScheduleJob(job, trigger);
            }
            catch (Exception ex)
            {
                EE.LogError($"Schedule {interval} seconds Job fail，type={typeof(T)}jobName={jobName}，interval={interval}", ex, log);
            }
        }
    }
}
